﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;


namespace CCPSIP.Message
{
    /// <summary>CCPSIP_032：機器人傳送文字訊息 API</summary>
    /// SERVICE_ID = 機器人服務ID。
    /// Password = 機器人服務密碼。
    /// ChatID = 聊天ID（User 的 SIP_Num）。
    /// PPS_CODE = User 的員工編號。
    /// MobileNum = User 的手機門號（含國碼）。
    /// MsgType = 訊息類型，目前支援 ("T", "Q[1-9A-Z]")。(Text, QR code) (Q1=靜態，Q2=動態)
    /// message = 訊息全文。
    /// （ChatID / PPS_CODE / MobileNum至少須傳其中一個）

    public class robot_send_text : IHttpHandler
    {
        private const int kMsgPreviewLength = 20;
        private const string kDateTimeFormat = "yyyy/MM/dd HH:mm:ss";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】檢查呼叫端的 IP Address 是否合法
                //
                string ipAddr = ChrisKit.getIPAddress(req);
                if (!RobotKit.isAllowRobotIP(ipAddr))
                {
                    throw new Exception("ERROR_01: Access Denied");//拒絕存取
                }


                //【02】取得POST參數，驗證身分
                //
                string SERVICE_ID = req.Form["SERVICE_ID"];//機器人服務ID
                string Password = req.Form["Password"];    //機器人服務密碼
                string ChatID = req.Form["ChatID"];      //聊天ID(對方帳號或ClientGID)
                string PPS_CODE = req.Form["PPS_CODE"];  //長春員工編號
                string MobileNum = req.Form["MobileNum"];//接收方的手機號碼(含國碼)
                string MsgType = req.Form["MsgType"];//訊息類型
                string message = req.Form["message"];//訊息全文
                int localPID = -1;//發訊方的本機訊息ID

                RobotServiceInfo rService = RobotKit.getServiceInfo(SERVICE_ID, Password);
                if (rService == null)
                {
                    throw new Exception("ERROR_02: Service Authentication Failed");//服務認證失敗
                }

                if (string.IsNullOrEmpty(message))
                {
                    throw new Exception("ERROR_03: Message cannot be empty");//訊息不可空白
                }

                string ROBOT_ID = rService.ROBOT_ID;


                //【03】檢查UserID
                //
                if (string.IsNullOrEmpty(ChatID))
                {
                    string[] UserIDs;
                    if (string.IsNullOrEmpty(PPS_CODE))
                        UserIDs = OracleKitUser.getUserIDbyMobile(MobileNum);
                    else
                        UserIDs = OracleKitUser.getUserIDbyEmpID(PPS_CODE);

                    if (UserIDs != null && UserIDs.Length > 0)
                        ChatID = UserIDs[0];
                }

                if (!OracleKitUser.hasUser(ChatID))
                {
                    throw new Exception("ERROR_04: User not found");//找不到User
                }


                //【04】產生訊息摘要
                //
                string msgPreview = message.Replace("\r\n", " ").Replace("\n", " ");
                if (MsgType == "T")
                {
                    if (msgPreview.Length > kMsgPreviewLength)
                        msgPreview = msgPreview.Substring(0, kMsgPreviewLength - 3) + "...";
                    msgPreview = string.Format("{0}: {1}", rService.ROBOT_CNAME, msgPreview);
                }
                else if (Regex.IsMatch(MsgType, "^Q[1-9A-Z]$"))
                {
                    msgPreview = string.Format("{0} sent you a QR code.", rService.ROBOT_CNAME);
                }
                else
                {
                    throw new Exception("ERROR_05: Message type not support");//不支援的訊息類型
                }


                //【05】儲存訊息
                //
                long MsgID = OracleKitMsg.InsertMsgOne(ROBOT_ID, ChatID, MsgType, msgPreview, message, localPID, reqTime);


                //【06】Log機器人回覆
                //
                OracleKitRobot.InsertMsgOneRobot("R", ChatID, ROBOT_ID, SERVICE_ID, MsgID, message, reqTime);


                //【97】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【98】傳送 Windows CCP MSG 通知
                //
                if (SipKit.isHQMobileExt(ChatID))
                {
                    MSGKit.SendTextHQAsync(ChatID, msgPreview);
                }


                //【99】回傳結果
                //
                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                resultDict["MsgID"] = Convert.ToString(MsgID);
                resultDict["MsgTime"] = reqTime.ToString(kDateTimeFormat);

                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(resultDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
